//
//  ZJKStatusListViewModel.swift
//  MicroBlog
//
//  Created by VAD on 16/4/20.
//  Copyright © 2016年 朱江坤. All rights reserved.
//

import UIKit
import SDWebImage

class ZJKStatusListViewModel: NSObject {
    
    //定义保存数据的数组
    var statusArray: [ZJKStatusViewModel]?
    
    //下载数据的方法
    func loadData(isPullup: Bool,finished: (isSucess: Bool)->()){
        //接口地址
        let urlString = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        var max_id: Int64 = 0
        
        var since_id: Int64 = 0
        
        if isPullup {
            max_id = statusArray?.last?.status?.id ?? 0
            // 去除重复：若指定此参数，则返回ID小于或 “等于” max_id的微博，默认为0
            if max_id != 0{
                max_id--
            }
        }else{
            
            since_id = statusArray?.first?.status?.id ?? 0
            
        }
        //设置访问参数
        let params = ["access_token": ZJKUserAccountViewModel.sharedViewModel.accessToken ?? "",
        "max_id": "\(max_id)",
        "since_id": "\(since_id)"]
        
        
        //发送请求
        HMNetworkTools.sharedTools.request(urlString: urlString, parameters: params) { (responseObject, error) -> () in
            
            if error != nil{
                
                return
            }
            guard let responseDict = responseObject as? [String: AnyObject] else {
                
                finished(isSucess: false)
                
                return
            }
            
            // 1. 取出 statuses 对应该节点的数据 （字典数组）
            guard let dicts = responseDict["statuses"] as? [[String: AnyObject]] else {
                
                finished(isSucess: false)
                
                return
            }
            
            // 2. 遍历字典数组，进行字典转模型
            // 初始化空数组
            var tempArray = [ZJKStatusViewModel]()
            
            for value in dicts {
                
                // 转成模型
                let status = ZJKStatus(dict: value)
                
                // 初始化一个ViewModel
                let viewModel = ZJKStatusViewModel()
                
                // 设置模型到ViewModel里面去
                viewModel.status = status
                
                tempArray.append(viewModel)
                
            }
            
            //给当前的保存数据的数组赋值
//            self.statusArray = tempArray
            if self.statusArray == nil {
                self.statusArray = [ZJKStatusViewModel]()
            }
            
            //判断是否是上拉加载
            if isPullup{
                self.statusArray = self.statusArray! + tempArray
            }else{
                self.statusArray = tempArray + self.statusArray!
            }
            
            
             print("加载回来：\(tempArray.count)条")
//            //回调闭包
//            finished(isSucess: true)
            self.cacheSingleImage(tempArray, finished: finished)
        }
    }
    //缓存单张图片
    private func cacheSingleImage(array: [ZJKStatusViewModel],finished: (isSucess: Bool)->()){
        
        let group = dispatch_group_create()
        
        for value in array{
            // 1. 遍历判断图片数组是否是单张
            
            // 是取原创微博的图片还是转发微博的图片
            let originalPicUrls = value.status?.pic_urls
            let retweetPicurls = value.status?.retweeted_status?.pic_urls
            
            // 取到图片数组
            let picUrls = (originalPicUrls == nil || originalPicUrls!.count == 0) ? retweetPicurls : originalPicUrls

            if picUrls?.count == 1 {
                let urlString = picUrls?.first?.thumbnail_pic
                print(urlString)
                
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string: urlString ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                    // - 更新单张图片的配图视图的大小
                    value.updateSingleImagePictureViewSize()
                    // 拿出来一个鸡蛋
                    dispatch_group_leave(group)
                })
            }
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue()) { () -> Void in
            finished(isSucess: true)
        }
        
    }

}
